const { orderCount, wechatUsers, Products } = require('../../schemas')
const { commonMonitor } = require('./monitor')

const { getDateCount } = require('../../utils')

// 微信 统计 详情
const wechatCount = async (request, reply) => {
  const { days } = request.query

  try {
    const RegisteredUserCount = await getDateCount(
      wechatUsers,
      days,
      '注册用户'
    ) // 微信用户 统计
    const OrderQuantityStatistics = await getDateCount(
      orderCount,
      days,
      '订单量'
    ) // 微信 订单 下单 统计

    // 微信 访问 统计
    if (OrderQuantityStatistics.message || RegisteredUserCount.message) {
      return reply.code(404).send({
        code: reply.statusCode,
        message: 'error',
        data: null,
        error: OrderQuantityStatistics.message || RegisteredUserCount.message,
      })
    }

    return reply.code(200).send({
      code: reply.statusCode,
      message: 'success',
      data: {
        orderCount: OrderQuantityStatistics,
        userCount: RegisteredUserCount,
      },
      error: null,
    })
  } catch (error) {
    return reply.code(404).send({
      code: reply.statusCode,
      message: 'error',
      data: null,
      error: error,
    })
  }
}
const commonAdminHomeCount = async (request, reply) => {
  // 1. 微信 订单 总量  今日 订单量
  // 2. 微信 注册用户 总量 今日注册用户量
  // 3. 微信 访问 总量 今日访问量
  // 4. admin 产品 总量

  try {
    const data = []
    const order = await computed(orderCount, '微信订单量', '今日订单量')
    const user = await computed(wechatUsers, '微信注册用户量', '今日注册用户量')
    const product = await computed(Products, '微信产品总量', '今日产品总量')
    data.push(order, user, product)

    return reply.code(200).send({
      code: reply.statusCode,
      message: 'success',
      data,
      error: null,
    })
  } catch (error) {
    return reply.code(404).send({
      code: reply.statusCode,
      message: 'error',
      data: null,
      error: error,
    })
  }
}

module.exports = {
  wechatCount,
  commonAdminHomeCount,
  commonMonitor,
}

async function computed(modal, title, subtitle) {
  const today = new Date()
  today.setHours(0, 0, 0, 0) // 设置为本地时间的今日00:00:00

  const count = await modal.countDocuments()
  const todayCount = await orderCount.countDocuments({
    createdAt: { $gte: today },
  })
  return {
    title,
    subtitle,
    count,
    todayCount,
  }
}
